import { EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { App, DatePicker, Form, Input, Select } from 'antd';
import OrderServices, { EditOrderParams } from '@/api/services/workOrderServices';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useCatch } from '@/hooks';
import dayjs, { Dayjs } from 'dayjs';

export type EditOrderModalRef = {
  open: (
    params: Pick<EditOrderParams, 'id'> &
      Pick<EditOrderParams, 'alarmId'> &
      Pick<EditOrderParams, 'reportId'>,
  ) => void;
};

type Props = {
  callback: () => void;
};

interface FormInstance {
  name: string;
  headId: number;
  date: [Dayjs, Dayjs];
  remarks?: string;
}

const EditOrderModal = forwardRef<EditOrderModalRef, Props>(({ callback }, ref) => {
  const { message } = App.useApp();
  const theme = useTheme();
  const [form] = Form.useForm<FormInstance>();
  const catchFn = useCatch();

  const [orderId, setOrderId] = useState<number>();
  const alarmId = useRef<number>();
  const reportId = useRef<number>();
  const [open, setOpen] = useState(false);

  const { data: orderInfo, isFetching } = useQuery({
    queryKey: ['order-detail', orderId],
    queryFn: () => catchFn(() => OrderServices.getDetail(orderId!)),
    select: ({ data }) =>
      ({
        name: data.name,
        headId: data.headId,
        date: [dayjs(data.beginTime), dayjs(data.endTime)],
        remarks: data.remarks,
      }) as FormInstance,
    enabled: !!orderId,
    staleTime: 0,
  });

  useEffect(() => {
    if (orderInfo) form.setFieldsValue(orderInfo);
  }, [orderInfo]);

  const { data: headerOptions } = useQuery({
    queryKey: ['header-list'],
    queryFn: () => catchFn(() => OrderServices.getHeaderList()),
    select: ({ data }) => data.map((item) => ({ label: item.name, value: item.id })),
  });

  const { mutate: create, isPending: createLoading } = useMutation({
    mutationFn: OrderServices.create,
    onSuccess: () => {
      message.success('创建工单成功');
      close();
      callback();
    },
    onError: (error) => message.error(error.message),
  });

  const { mutate: update, isPending: updateLoading } = useMutation({
    mutationFn: OrderServices.update,
    onSuccess: () => {
      message.success('修改工单成功');
      close();
      callback();
    },
    onError: (error) => message.error(error.message),
  });

  const handleSubmit = async () => {
    await form.validateFields();
    const data = form.getFieldsValue();

    if (orderId) {
      update({
        id: orderId,
        alarmId: alarmId.current!,
        reportId: reportId.current!,
        headId: data.headId,
        beginTime: data.date[0].format('YYYY-MM-DD'),
        endTime: data.date[1].format('YYYY-MM-DD'),
        name: data.name,
        remarks: data.remarks,
      });
    } else {
      create({
        alarmId: alarmId.current!,
        reportId: reportId.current!,
        headId: data.headId,
        beginTime: data.date[0].format('YYYY-MM-DD'),
        endTime: data.date[1].format('YYYY-MM-DD'),
        name: data.name,
        remarks: data.remarks,
      });
    }
  };

  const close = () => {
    setOpen(false);
    setOrderId(undefined);
    alarmId.current = undefined;
    reportId.current = undefined;
    form.resetFields();
  };

  useImperativeHandle(ref, () => ({
    open: ({ id, alarmId: _alarmId, reportId: _reportId }) => {
      if (id) setOrderId(id);
      alarmId.current = _alarmId;
      reportId.current = _reportId;
      setOpen(true);
    },
  }));

  return (
    <>
      <EditModal
        title={orderId ? '修改工单' : '创建工单'}
        theme={theme}
        open={open}
        onClose={close}
        onCancel={close}
        forceRender
        loading={isFetching}
        confirmLoading={createLoading || updateLoading}
        onOk={handleSubmit}
        modalRender={(dom) => (
          <Form form={form} layout="vertical" initialValues={{ userBlock: false }}>
            {dom}
          </Form>
        )}
      >
        <Form.Item
          label="工单名称"
          name="name"
          rules={[{ required: true, message: '请填写工单名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="养护负责人"
          name="headId"
          rules={[{ required: true, message: '请选择养护负责人' }]}
        >
          <Select options={headerOptions} />
        </Form.Item>
        <Form.Item
          label="计划时间"
          name="date"
          rules={[{ required: true, message: '请选择计划时间' }]}
        >
          <DatePicker.RangePicker
            className="w-full"
            disabledDate={(current) => {
              return current.valueOf() < dayjs().subtract(1, 'day').valueOf();
            }}
          />
        </Form.Item>
        <Form.Item label="备注" name="remarks">
          <Input.TextArea />
        </Form.Item>
      </EditModal>
    </>
  );
});

export default EditOrderModal;
